﻿//暂时先不考虑IO失败的操作
#pragma once

#include <qobject.h>
#include <qfile.h>
#include <qthread.h>

#include "DataQueue.h"

class FileData
{
private:
	QString filePath = "";
	QByteArray data;
	QFile::OpenModeFlag openModeFlag;
public:
	explicit FileData();
	explicit FileData(QString filePath, QByteArray data, QFile::OpenModeFlag openModeFlag);
	virtual ~FileData();

public:
	QString getFilePath();
	void setFilePath(QString& filePath);
	QByteArray getData();
	void setData(QByteArray& data);
	QFile::OpenModeFlag getOpenModeFlag();
	void setOpenModeFlag(QFile::OpenModeFlag openModeFlag);
};

class FileWriter : public QThread
{
	Q_OBJECT
public:
	enum SaveFileMode
	{
		WriteToFile,
		AppendToFile
	};
private:
	DataQueue<FileData*>  dataQueue;
	bool isStart = false;
public:
	explicit FileWriter(QObject* parent = Q_NULLPTR);
	virtual ~FileWriter();

public:
	void saveAsFileNoWait(QString filePath, QByteArray data, SaveFileMode saveFileMode = AppendToFile);//多线程写
	bool saveAsFile(QString filePath, QByteArray data, SaveFileMode saveFileMode = AppendToFile);//单线程写
private:
	bool _saveAsFile(QString filePath, QByteArray data, QFile::OpenModeFlag openModeFlag = QFile::Append);
protected:
	virtual void run()override;
private:
	static QFile::OpenModeFlag getOpenMode(SaveFileMode saveFileMode)
	{
		switch (saveFileMode)
		{
		case FileWriter::WriteToFile:
			return QFile::WriteOnly;
		case FileWriter::AppendToFile:
			return QFile::Append;
		default:
			return QFile::Append;
		}
	}
};
